package com.dfqy.front;

import com.dfqy.pojo.*;
import com.dfqy.service.*;
import com.dfqy.vo.Result;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Author : atyushu
 * Package : com.dfqy.front
 * ClassName : JoinFrontController
 * Create : 2023/8/2 - 19:49
 * Version : v1.0
 * Description : The class of controller for join.
 */
@Validated
@RestController
@Api(tags = "JoinFrontController", description = "预约活动讲座, (官网无示例参考, 表单设计, 请根据Join实体类中的字段，自由发挥)")
@RequestMapping("front/join")
public class JoinFrontController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JoinService joinService;

    @Autowired
    private UserService userService;

    @Autowired
    private EventService eventService;

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        simpleDateFormat.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
    }

    @ApiOperation("预约活动讲座, (着重注意: 日期的处理, 后端接收的格式为<yyyy-MM-dd HH:mm>, 对应前端表单中 <input type='datetime-local'>, 然而此标签, 获取用户输入的日期后, 会将此格式中的空格解析为'T', 例如<2023-8-9T9:10>, 因此在提交传输前, 务必将此'T'截掉, 例如: data.jointime = document.getElementById('jointime').value.replace('T', ' ');  ), (务必包含的参数: jointime<参加时间> , phone<联系方式> , uname<参加人> , eventid<活动号！！！！！！>)")
    @PostMapping("insert")
    public Result insert(@RequestBody Join join, HttpServletRequest request) {
        if (new Date().getTime() >= eventService.getById(join.getEventid()).getFinishtime().getTime()) {
            return Result.error("活动已结束");
        }
        if (join.getJointime().getTime() >= eventService.getById(join.getEventid()).getFinishtime().getTime()) {
            return Result.error("预约时间，不得在活动结束之后");
        }
        String token = request.getHeader("Authorization");
        if (token != null && redisTemplate.opsForValue().get(token) != null) {
            User user = (User) redisTemplate.opsForValue().get(token);
            user.setScore(user.getScore() + 10);
            userService.update(user);
            join.setUserid(user.getId());
            redisTemplate.opsForValue().set(token, user);
        }
        int insert = joinService.insert(join);
        return insert > 0 ? Result.success("预约成功") : Result.error("预约失败");
    }
}